<template>
  <div class="page-container">
    <section class="content-container">
      <header class="page-header">
        <h2>课程列表</h2>
      </header>

      <ul class="product-list">
        <li v-for="product in productList" :key="product.id">
          <button :class="['product-btn', { active: payOrder.productId === product.id }]"
            @click="selectItem(product.id)">
            <span class="product-title">{{ product.title }}</span>
            <span class="product-price">¥{{ product.price }}</span>
          </button>
        </li>
      </ul>

      <div class="payment-methods">
        <h3>选择支付方式</h3>
        <div class="method-options">
          <!-- 微信支付 -->
          <div :class="['method-option', { active: payOrder.payType === 'wxpay' }]" @click="selectPayType('wxpay')">
            <img src="@/assets/img/wxpay.png" class="method-icon">
            <div class="method-info">
              <div class="method-name">微信支付</div>
            </div>
          </div>

          <!-- 支付宝 -->
          <div :class="['method-option', { active: payOrder.payType === 'alipay' }]" @click="selectPayType('alipay')">
            <img src="@/assets/img/alipay.png" class="method-icon">
            <div class="method-info">
              <div class="method-name">支付宝</div>
            </div>
          </div>
        </div>
      </div>

      <div class="payment-actions">
        <el-button :disabled="payBtnDisabled" type="primary" size="large" round @click="toPay()">
          确认支付
        </el-button>
      </div>
    </section>

    <!-- 微信支付二维码 -->
    <el-dialog v-model="codeDialogVisible" :show-close="false" @close="closeDialog" width="350px" center>
      <div class="qrcode-container">
        <qrcode-vue :value="codeUrl" :size="200" level="H" />
      </div>
      <p class="qrcode-tip">使用微信扫码支付</p>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { getProductList } from '@/api/product'
import { nativePayService } from '@/api/wxPay'
import { aliPayPayService } from '@/api/aliPay'
import { getOrderStatus } from '@/api/orderInfo'
import QrcodeVue from 'qrcode.vue'
import { ElMessage } from 'element-plus'

const router = useRouter()

const payBtnDisabled = ref(false)
const codeDialogVisible = ref(false)
const productList = ref([])
const payOrder = ref({
  productId: '',
  payType: 'wxpay'
})
const codeUrl = ref('')
const orderNo = ref('')
const timer = ref(null)

onMounted(async () => {
  try {
    const response = await getProductList()
    productList.value = response.data
    if (productList.value.length > 0) {
      payOrder.value.productId = productList.value[0].id
    }
  } catch (error) {
    console.error('获取商品列表失败:', error)
    ElMessage.error('获取商品列表失败')
  }
})

const selectItem = (productId) => {
  payOrder.value.productId = productId
}

const selectPayType = (type) => {
  payOrder.value.payType = type
}

const toPay = async () => {
  payBtnDisabled.value = true
  if (payOrder.value.payType === 'wxpay') {
    try {
      const response = await nativePayService(payOrder.value.productId)
      codeUrl.value = response.data.codeUrl
      orderNo.value = response.data.orderNo
      codeDialogVisible.value = true

      timer.value = setInterval(() => {
        queryOrderStatus()
      }, 3000)
    } catch (error) {
      console.error('支付失败:', error)
      ElMessage.error('支付失败，请重试')
      payBtnDisabled.value = false
    }
  } else if (payOrder.value.payType === 'alipay') {
    //调用支付宝统一收单下单并支付页面接口
    aliPayPayService(payOrder.value.productId).then((response) => {
      //将支付宝返回的表单字符串写在浏览器中，表单会自动触发submit提交
      //方法一：
      // document.write(response.data)

      //方法二：
      const parser = new DOMParser();
      const doc = parser.parseFromString(response.data, 'text/html');
      const forms = doc.querySelectorAll('form');
      if (forms.length > 0) {
        document.body.appendChild(forms[0]);
        forms[0].submit();
        setTimeout(() => document.body.removeChild(forms[0]), 1000);
      }
    })
  }
}

const closeDialog = () => {
  payBtnDisabled.value = false
  clearInterval(timer.value)
}

const queryOrderStatus = async () => {
  try {
    const response = await getOrderStatus(orderNo.value)
    if (response.code === 200) {
      clearInterval(timer.value)
      ElMessage.success('支付成功')
      codeDialogVisible.value = false // 关闭弹窗
      payBtnDisabled.value = false // 重置支付按钮状态
    }
  } catch (error) {
    console.error('查询订单状态失败:', error)
  }
}
</script>

<style scoped>
.page-container {
  background-color: #f8fafc;
  min-height: 100vh;
  padding: 24px;
}

.content-container {
  max-width: 1200px;
  margin: 0 auto;
  background: #fff;
  padding: 32px;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.page-header {
  margin-bottom: 32px;
  text-align: center;
}

.page-header h2 {
  font-size: 28px;
  font-weight: 600;
  color: #1a1a1a;
  margin: 0;
}

.product-list {
  list-style: none;
  padding: 0;
  margin: 0 0 32px 0;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
}

.product-btn {
  display: flex;
  flex-direction: column;
  width: 100%;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  color: #333;
  text-align: left;
  border: 1px solid #e2e8f0;
  cursor: pointer;
  transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.product-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border-color: #cbd5e1;
}

.product-btn.active {
  background: #f0f9ff;
  border-color: #7dd3fc;
  color: #0369a1;
  box-shadow: 0 4px 12px rgba(3, 105, 161, 0.1);
}

.product-title {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 8px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.product-price {
  font-size: 18px;
  font-weight: 600;
  color: #0ea5e9;
}

.payment-methods {
  margin-bottom: 32px;
}

.payment-methods h3 {
  font-size: 20px;
  font-weight: 500;
  color: #1a1a1a;
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f1f5f9;
}

.method-options {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  gap: 20px;
}

.method-option {
  display: flex;
  align-items: center;
  padding: 16px;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
  background: #fff;
}

.method-option:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  border-color: #cbd5e1;
}

.method-option.active {
  border-color: #0ea5e9;
  background-color: #f0f9ff;
  box-shadow: 0 4px 12px rgba(14, 165, 233, 0.1);
}

.method-icon {
  width: 36px;
  height: 36px;
  margin-right: 16px;
  object-fit: contain;
}

.method-name {
  font-size: 16px;
  font-weight: 500;
  color: #1a1a1a;
}

.payment-actions {
  display: flex;
  justify-content: center;
  margin-top: 32px;
}

.qrcode-container {
  margin: 0 auto 20px;
  display: flex;
  justify-content: center;
  padding: 12px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.qrcode-tip {
  text-align: center;
  font-size: 16px;
  color: #64748b;
  margin-top: 12px;
}
</style>